<template>
  <view class="login" :style="pageHeight">
    <image :src="vuex_imgPath+'/login_bg.png'" class="login-bg" />
    <view class="login-int">
      <view class="t-int">手机号码</view>
      <view class="login-int-box">
        <uni-easyinput
          v-model="phone"
          font-size="28rpx"
          :input-border="false"
          :trim="true"
          clear-size="18"
          clearable
          placeholder="请输入手机号"
          placeholder-style="color: #999"
        />
      </view>
    </view>
    <view class="login-int">
      <view class="t-int">验证码</view>
      <view class="login-int-box">
        <view class="verode-box">
          <uni-easyinput
            v-model="code"
            font-size="28rpx"
            :input-border="false"
            :trim="true"
            clear-size="18"
            clearable
            placeholder="短信验证码"
            placeholder-style="color: #999"
          />
        </view>
        <view class="verode" @click="checkTel">{{ getCodeName }}</view>
      </view>
    </view>
    <view class="login-int">
      <view class="t-int">密码</view>
      <view class="login-int-box">
        <view class="password-box">
          <uni-easyinput
            v-model="password"
            :type="!isShowPassword ? 'password' : 'text'"
            clearable
            :input-border="false"
            :password-icon="false"
            :trim="true"
            clear-size="18"
            placeholder="登录密码"
            font-size="28rpx"
            placeholder-style="color: #999"
          />
        </view>
        <image
          class="password-change"
          :src="!isShowPassword ? openEyeIcon : closeEyeIcon"
          @click="changeInputTypeFn"
        />
      </view>
    </view>
    <view class="login-btn">
      <button type="default" :plain="true" class="login-box login-org btn-noborder login-org-curr" @click="setMemberNewPwdFn">确定</button>
    </view>

    <!-- #ifdef H5 -->
    <view>
      <view>
        <!--组件-->
        <slideVerify v-if="slideShowStatus" @seccess="slideYzSeccess" />
      </view>
    </view>
    <!-- #endif -->
  </view>
</template>

<script>
import {
  updatePwdForH5,
  sendVerifyCode,
  existPhone,
  traceless
} from '@/api/login.js';
import { phoneTestFn, passwordTestFn } from '@/login/loginCommonFn'
import { initSlide } from '@/common/common'
import { Base64 } from '@/lib/Base64';
import slideVerify from '@/components/slide-verify.vue';
import '@/static/scss/login.scss';

export default {
  name: 'PasswordLogin',
  components: {
    slideVerify
  },
  data() {
    return {
      pageHeight: '',
      getCodeName: '获取验证码',
      codeFlag: true,
      phone: '',
      code: '',
      password: '',
      isShowPassword: false, // 是否展示密码
      closeEyeIcon: '/static/shopIcon/close_eye.png', //闭眼icon地址
      openEyeIcon: '/static/shopIcon/open_eye.png', //睁眼icon地址
      type: '',
      callbackUrl: '',
      urlParams: '',
      registParams: '',
      curUuid: '',
      slideShowStatus: false,
      clicktime: true
    }
  },
  onShow() {
    // #ifdef MP-ALIPAY
    if (uni.getStorageSync('inviteCode')) {
      this.callbackUrl = '/shopIndex/shopIndex' //扫门店二维码注册跳转云采首页
      this.type = 'ground'
    }
    // #endif
    this.curUuid = this.randomNumber(10);
  },
  onLoad(option) {
    const { type = '', callbackUrl = '', urlParams = '' } = option
    this.type = type
    this.callbackUrl = callbackUrl
    this.urlParams = urlParams == '' ? {} : JSON.parse(urlParams)
    // #ifdef MP-WEIXIN
    if (uni.getStorageSync('inviteCode')) {
      this.callbackUrl = '/shopIndex/shopIndex' //扫门店二维码注册跳转云采首页
      this.type = 'ground'
    }
    // #endif
    //#ifdef H5
    //initSlide()
    // #endif
  },
  onPullDownRefresh(e) {
    uni.redirectTo({
      url: `/login/resetPassword/index`,
    });
    setTimeout(function() {
      uni.stopPullDownRefresh();
    }, 1000);
  },
  methods: {
    /*修改密码输入框类型*/
    changeInputTypeFn() {
      this.isShowPassword = !this.isShowPassword
    },
    getMobileVerifyCodeFn() {
      let timer = null
      if (!phoneTestFn(this.phone)) {
        this.$u.toast('请输入正确的手机号');
        return
      }
      if (!this.codeFlag) {
        return
      }
      const params = {
        'duration': 300,
        'length': 4,
        'phone': this.phone,
        'templateId': 3,
        'uuid': this.curUuid
      }
      const that = this
      sendVerifyCode(params).then((res) => {
        if (res.code == 0) {
          timer = that.countDownFn(60)
          return this.$u.toast('发送成功')
        } else {
          clearInterval(timer)
          this.getCodeName = `获取验证码`
          this.codeFlag = true
          return this.$u.toast(res.msg)
        }
      })
    },
    countDownFn(num) {
      const timer = setInterval(() => {
        if (num > 0) {
          num--
          this.getCodeName = `${num}秒后重新获取`
          this.codeFlag = false
        } else {
          clearInterval(timer)
          this.getCodeName = `获取验证码`
          this.codeFlag = true
        }
      }, 1000)
      return timer
    },
    setMemberNewPwdFn() {
      const _this = this
      if (!phoneTestFn(this.phone)) {
        this.$u.toast('请输入正确的手机号')
        return
      }
      if (!this.code) {
        this.$u.toast('验证码不能为空')
        return
      }
      if (!passwordTestFn(this.password)) {
        return
      }
      // // #ifdef H5
      // window.nvc.getNVCValAsync(function(nvcVal) {
      //   console.log('点击获取验证码掉无痕')
      //   if (_this.slideShowStatus == true) {
      //     _this.slideShowStatus = false
      //   }
      //   _this.tranClassFn(decodeURIComponent(nvcVal))
      // });
      // // #endif
      this.updatePwdForH5Fn()
    },
    updatePwdForH5Fn() {
      var params = {
        phone: this.phone,
        verifyCode: this.code,
        newPwd: Base64.encode(this.password),
        uuid: this.curUuid,
        verifyMethod: 3,
        loginAccount: this.phone,
      }
      updatePwdForH5(params).then((res) => {
        if (res.code == 0) {
          this.$u.toast('修改成功')
          setTimeout(() => {
            uni.redirectTo({
              url: '/login/resetPassword/resetPasswordSucess'
            });
          }, 2000)
        } else {
          this.$u.toast(res.msg)
        }
      })
    },
    /*检查手机号是否存在*/
    checkTel() {
      const params = {
        'phone': this.phone
      };
      existPhone(params).then((res) => {
        if (res.code == 0) {
          this.getMobileVerifyCodeFn()
        } else {
          this.$u.toast(res.msg)
        }
      })
    },
    /*生成uuid*/
    randomNumber(len) {
      const chars = '0123456789';
      const maxPos = chars.length;
      let str = '';
      for (let i = 0; i < len; i++) {
        str += chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return str;
    },
    tranClassFn(parame) {
      traceless({ nvcVal: parame }).then((res) => {
        this.resultTrace(res);
      }).catch(() => {
        // eslint-disable-next-line no-mixed-spaces-and-tabs
      })
    },
    resultTrace(res) {
      if (res.data == 200 || res.data == 100) {
        //验证通过
        this.updatePwdForH5Fn()
        return;
      }

      if (res.data == 400) {
        //验证不通过
        var ncoption = {
          // 声明滑动验证需要渲染的目标ID。
          renderTo: 'nc',
        }
        // 唤醒二次验证（滑动验证码）
        window.nvc.getNC(ncoption);
        this.slideShowStatus = true
        return;
      }

      if (res.data == 900) {
        //二次验证验证不通过
        console.log('验证失败', 3000);
        return;
      }

      if (res.data == 800) {
        //直接拦截
        console.log('您的账号存在异常，请联系在线客服！', 3000);
        return;
      }
    },
    //接无痕验证收验证成功的值
    slideYzSeccess(data) {
      console.log('400时出现的滑块 当移动滑块成功之后返回')
      //会话ID（sessionId）、签名串（sig）、请求唯一标识（token）
      console.log(data.sessionId)
      console.log(data.sig)
      console.log(data.token)
      this.updatePwdForH5Fn()
    },
  }
}
</script>

<style scoped lang="scss">
.login{
  padding-top: 50rpx;
}
.login-int-box{
  position: relative;
  border: 2rpx solid $uni-grey-e2!important;
  /deep/ .uni-easyinput {
    padding: 0 !important;
    /deep/ .uniui-clear{
      color: #c0c4cc;
    }
  }
  /deep/ input {
    height:72rpx;
    padding: 0 32rpx;
  }
  .verode-box {
    /deep/ .uni-easyinput__content{
      width: 300rpx;
    }
  }
  .password-box{
    width:584rpx;
    /deep/ .uni-easyinput__content{
      width: 524rpx;
    }
  }
  .password-change{
    position: absolute;
    width: 32rpx;
    height: 32rpx;
    top: 20rpx;
    right: 24rpx;
  }
}
</style>
